use std::sync::mpsc::{Sender, Receiver};
use specs::{System, Entities, ReadStorage, Component};
use specs::world::Index;
use crate::res::owner_storage::Owner;

#[derive(Clone)]
pub struct GetPlayerMessage<T: Component>
{
    to: Sender<T>,
    who: Index,
}

impl<T: Component> GetPlayerMessage<T>
{
    pub fn new(to: Sender<T>, who: Index) -> GetPlayerMessage<T> {
        GetPlayerMessage {
            to,
            who,
        }
    }
}

pub struct GetPlayerSystem<T: Component>
{
    rc: Receiver<GetPlayerMessage<T>>,
}

impl<T: Component> GetPlayerSystem<T>
{
    pub fn new(rc: Receiver<GetPlayerMessage<T>>) -> Self {
        GetPlayerSystem {
            rc
        }
    }
}

impl<'a, T: Component + Clone> System<'a> for GetPlayerSystem<T>
{
    type SystemData = (
        Entities<'a>,
        ReadStorage<'a, T>,
    );

    fn run(&mut self, data: Self::SystemData) {
        let (entities, value_storage) = data;

        if let Ok(report) = self.rc.try_recv() {
            let player = entities.entity(report.who);
            
            if let Some(value) = value_storage.get(player) {
                report.to.send(value.clone()).unwrap();
            }
        }
    }
}
